package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"manager/bll"
	"manager/model"
	"manager/server/web/middleware"
	"manager/utils"
)

var UserBikeSetting = &userBikeSetting{}

func init() {
	// 注册路由
	RegisterRouter(UserBikeSetting)
}

type userBikeSetting struct{}

// Init 初始化路由
func (a *userBikeSetting) Init(r *gin.RouterGroup) {
	// web 路由
	g := r.Group("/userBikeSetting", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
	// app 路由
	appG := r.Group("app/userBikeSetting", middleware.Auth())
	{
		appG.POST("/create", a.create)
		appG.POST("/update", a.update)
		appG.POST("/list", a.list)
		appG.POST("/delete", a.delete)
		appG.POST("/detail", a.find)
	}
}

// create 创建
func (a *userBikeSetting) create(c *gin.Context) {
	var (
		in  = &model.UserBikeSettingCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.UserBikeSetting.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update 更新
func (a *userBikeSetting) update(c *gin.Context) {
	var (
		in  = &model.UserBikeSettingUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 电动车名称不能为空
	if in.EbikeName != nil && *in.EbikeName == "" {
		c.Error(fmt.Errorf("电动车名称不能为空"))
		return
	}

	if err = bll.UserBikeSetting.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list 列表查询
func (a *userBikeSetting) list(c *gin.Context) {
	var (
		in  = &model.UserBikeSettingListRequest{}
		out = &model.UserBikeSettingListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.UserBikeSetting.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list 列表查询
func (a *userBikeSetting) find(c *gin.Context) {
	var (
		in  = &model.UserBikeSettingInfoRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	var rsp *model.UserBikeSettingListResponse
	if rsp, err = bll.UserBikeSetting.List(c.Request.Context(), &model.UserBikeSettingListRequest{
		Index:   1,
		Size:    1,
		EbikeId: in.EbikeId,
	}); err != nil {
		c.Error(err)
		return
	}

	if rsp != nil && len(rsp.List) > 0 {
		utils.ResponseOk(c, rsp.List[0])
		return
	}

	utils.ResponseOk(c, nil)
}

// delete 删除
func (a *userBikeSetting) delete(c *gin.Context) {
	var (
		in  = &model.UserBikeSettingDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.UserBikeSetting.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
